<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ include file="/public/header.jsp"%>
<%
    String callback = request.getParameter("callback");
	String isShow = request.getParameter("isShow") == null ? "" : request.getParameter("isShow");
	String id = request.getParameter("id") == null ? "" : request.getParameter("id");
	Map<String, Object> sessionMap = (Map<String, Object>) session.getAttribute("LOGIN_USER");
	String person_id = String.valueOf(sessionMap.get("id"));
	String person = String.valueOf(sessionMap.get("truename"));
	boolean isAdd = "".equals(id);
    int flag = 0;
    if(!isAdd){
    	flag = 1;
    }
%>
<html>
	<head>
		<title><%=isAdd?"新建公共费用报销申请":"编辑公共费用报销申请" %></title>
		<script type="text/javascript" src="<%=contextPath %>/public/js/extend.js"></script>
		<style>
			.td1{
				padding-top:10px;
				padding-bottom:5px;
				font-size: 12px;
				background-color: #c0ebd7;
				width:20%;
			}
			.td2{
				padding:5px;
			}
		</style>
	<script type="text/javascript">
	var gdAdminId="";
	var gdAdminName="";
		var lastIndex;
		$(function(){
			jQuery("#searchValue").keypress(function(e) { 
		    	// 回车键事件 
		     	if(e.which == 13) { 
		     		 doSearch();
		       	} 
		   	}); 
			jQuery("#p_dept_id").combotree({
				url:'<%=contextPath %>/springMVC/group/listDepartment',
				method:'POST',
				animate:true,
				lines:true,
				onChange:function(){
					doSearch();
				}
			});
		
			$("#company_id").combotree({
				url:'<%=contextPath %>/springMVC/group/getSystemTypeTree?type=8',
				method:'POST',
				animate:true,
				lines:true
			});
			
			var url="";
			if('<%=flag%>' == 1){
				jQuery('#ff').form({
					onLoadSuccess:function(data){
						gdAdminId=data.user_id;
						gdAdminName=data.user_name;
					}
				});
		    	jQuery('#ff').form('load','<%=contextPath%>/springMVC/finance/getFinanceCommonsById?id=<%=id%>');
		    	url="<%=contextPath%>/springMVC/finance/listFinanceCommonsDetail?commons_id=<%=id%>";
			}else{
				jQuery("#operation_time").datebox('setValue',getTodaySecond());
			}
			
			jQuery('#user_id').combogrid({
				title:'人员选择',
				mode:"remote",
				loadMsg:'正在加载数据，请稍后......',
				panelWidth:550,
				panelHeight:400,
				url:"<%=contextPath%>/springMVC/group/listPageUser",
				idField:"id",
				textField:"truename",
				rownumbers:true,
				fitColumns:true,
				columns: [[
					{field:'id',hidden:true},
					{field:'deptId',hidden:true},
					{field:'truename',title:'姓名',width:100},
					{field:'deptName',title:'所属部门',width:100},
					{field:'privName',title:'角色',width:100}
				]],
				toolbar:"#tb",
				pageSize:10,
				pageList:[10,50,100],  
				pagination:true,
				onLoadSuccess:function(rtJson){
					jQuery('#user_id').combogrid('setValue',gdAdminId);
					jQuery('#user_id').combogrid('setText',gdAdminName);
				}
			});
			
			 $('#table').datagrid({
		         	url:url,
					rownumbers:true,
					fitColumns:true,
					//showFooter:true,
					frozenColumns:[[
						{field:'ck',checkbox:true},
					    {title:'部门id',field:'dept_id',hidden:true},
					    {title:'类型id',field:'type_id',hidden:true}
					]],
					columns:[[
						{title:'费用科目',field:'type',width:200,align:'center',editor:{
							type:'combotree',
							options:{
								url:'<%=contextPath %>/springMVC/group/getSystemTypeTree?type=9',
								method:'POST',
								animate:true,
								lines:true,
								onClick:function(rowData){
									var pRow = $('#table').datagrid('getRows')[lastIndex];
									pRow.type_id = rowData.id;
									pRow.type = rowData.text;
									$('#table').datagrid('getData').rows[lastIndex]=pRow;
									var data = $('#table').datagrid('getData');
									$('#table').datagrid('loadData',data);
									
									$('#table').datagrid('endEdit', lastIndex);
									$('#table').datagrid('beginEdit', lastIndex);
									//lastIndex =-1;
								}
							}
						}},
						{title:'部门名称',field:'dept_name',width:250,align:'center',editor:{
							type:'combotree',
							options:{
								url: '<%=contextPath %>/springMVC/group/listDepartment',
								method:'POST',
								animate:true,
								lines:true,
								onClick:function(rowData){
									var pRow = $('#table').datagrid('getRows')[lastIndex];
									pRow.dept_id = rowData.id;
									pRow.dept_name = rowData.text;
									$('#table').datagrid('getData').rows[lastIndex]=pRow;
									var data = $('#table').datagrid('getData');
									$('#table').datagrid('loadData',data);
									
									$('#table').datagrid('endEdit', lastIndex);
									$('#table').datagrid('beginEdit', lastIndex);
									//lastIndex =-1;
								}
							}
						}},
						{title:'承担金额(元)',field:'money',width:200,align:'center',
							editor:{
								type:'numberbox',
								options:{
									 min:0,    
		    						 precision:2 
								}
						}},
						{title:'备注',field:'remark',width:200,align:'center',editor:{
							type:'textarea'
						}}
					]],
					onLoadSuccess:function(data){
						showMFooter();
					},
					onAfterEdit:function(){
						showMFooter();
					},
					onBeforeLoad:function(){
						$(this).datagrid('rejectChanges');
					},
					onClickCell:function(rowIndex,field,value){
						if (lastIndex != rowIndex){
							$('#table').datagrid('endEdit', lastIndex);
							$('#table').datagrid('beginEdit', rowIndex);
							var ed = $('#table').datagrid('getEditor', {index:rowIndex,field:field});
							if(ed == null){
								ed = $('#table').datagrid('getEditor', {index:rowIndex,field:'money'});
							}
							$(ed.target).select();
						}
						lastIndex = rowIndex;
					},
					toolbar:[
						{
							id:'add',
							text:'添加选项',
							disabled:false,
							iconCls:'icon-add',
							handler:function(){
								addRow();
							}
						},'-',{
						id:'save',
						text:'保存修改',
						disabled:false,
						iconCls:'icon-save',
						handler:function(){
							$('#table').datagrid('acceptChanges');
							lastIndex =-1;
						}
						},'-',{
						id:'delete',
						text:'删除',
						disabled:false,
						iconCls:'icon-remove',
						handler:function(){
							$('#table').datagrid('acceptChanges');
							lastIndex =-1;
							var rows = $('#table').datagrid('getSelections');
							if (rows.length > 0){
								for(var i=0;i<rows.length;i++){
									var row = rows[i];
									var index = $('#table').datagrid('getRowIndex', row);
									$('#table').datagrid('deleteRow', index);
								}
							}
							var data = $('#table').datagrid('getData');
							$('#table').datagrid('loadData',data);
						}
					}
				   ]
				});
				
			});
			
		function showMFooter(){
			var jsondata=jQuery("#table").datagrid("getData");
			var total = 0;
			for(var i=0;i<jsondata.rows.length;i++){
				if(jsondata.rows[i].money == null || jsondata.rows[i].money == ""){
					
				}else{
					total += parseFloat(jsondata.rows[i].money);
				}
			}
			$("#money").numberbox("setValue",total);
			/*
			jQuery('#table').datagrid('reloadFooter',[
			                              	{
			                              		dept_name:'合计:',
			                              		money: total 
			                              	 }
			                              ]);
			*/
		}
			function checkSameDept(rowData,rows){
				if (rows.length > 0){
					for(var i=0;i<rows.length;i++){
						if(rows[i].dept_id==rowData){
							return false;
						}
					}
				}
				return true;
			}
			function addRow(){
				$('#table').datagrid('endEdit', lastIndex);
				$('#table').datagrid('appendRow',{
				});
				var data = $('#table').datagrid('getData');
				$('#table').datagrid('loadData',data);
				lastIndex = $('#table').datagrid('getRows').length-1;
				$('#table').datagrid('selectRow', lastIndex);
				$('#table').datagrid('beginEdit', lastIndex);
			}
		function addXMInvoiceRequest(obj){
			//自动提交数据
			$('#table').datagrid('acceptChanges');
			lastIndex =-1;
			//自动提交数据
			var user_id=jQuery('#user_id').combogrid('getValue');
			var user_name=encodeURIComponent(jQuery('#user_id').combogrid('getText'));
			if(!checkNullOREmpty(user_id,"申请人")){return;}
			
			var company_id = $('#company_id').combotree('getValue');
			if(!checkNullOREmpty(company_id,"所属公司")){return;}
			
			var operation_time=jQuery("#operation_time").datebox('getValue');
			var money = $("#money").numberbox("getValue");
			if(money == "" ){
				$.messager.alert('提示','报销总额不能为空！');
				return ;
			}
			var summary=encodeURIComponent(jQuery('#summary').val());
			var is_all=jQuery("#is_all").val();
			var param = "user_id="+user_id+"&user_name="+user_name+"&company_id="+company_id+"&operation_time="+operation_time+"&is_all="+is_all+"&money="+money+"&summary="+summary;
			var evlaArr="";
			if(is_all == 0){
				var jsondata=$("#table").datagrid("getData");
				var moneyTotal = 0;
				for(var i=0;i<jsondata.total;i++){
					if(evlaArr!=""){
						evlaArr+=";";
					}
					evlaArr+=jsonToStr(jsondata.rows[i]);
					var index = $("#table").datagrid("getRowIndex",jsondata.rows[i])+1;
					if(jsondata.rows[i].type == null || jsondata.rows[i].type == ""){
						$.messager.alert('提示','第'+index+'行未选择费用科目！');
						return ;
					}
					else if(jsondata.rows[i].dept_name == null || jsondata.rows[i].dept_name == ""){
						$.messager.alert('提示','第'+index+'行未选择部门！');
						return ;
					}else if(jsondata.rows[i].money == null || jsondata.rows[i].money == "" ){
						$.messager.alert('提示','第'+index+'行承担金额填写不正确！');
						return ;
					}
					moneyTotal += parseFloat(jsondata.rows[i].money);
				}
				
				if(evlaArr == ""){
					$.messager.alert('提示',"请选择科目和部门！");
					return;
				}
				param += "&details="+encodeURIComponent(evlaArr);
			}
			if(is_all == 1){
				var jsondata=$("#table").datagrid("getData");
				var moneyTotal = 0;
				for(var i=0;i<jsondata.total;i++){
					if(evlaArr!=""){
						evlaArr+=";";
					}
					evlaArr+=jsonToStr(jsondata.rows[i]);
					var index = $("#table").datagrid("getRowIndex",jsondata.rows[i])+1;
					if(jsondata.rows[i].type == null || jsondata.rows[i].type == ""){
						$.messager.alert('提示','第'+index+'行未选择费用科目！');
						return ;
					}
					else if(jsondata.rows[i].dept_name != null && jsondata.rows[i].dept_name != ""){
						$.messager.alert('提示','第'+index+'行选择了部门！');
						return ;
					}
					else if(jsondata.rows[i].money == null || jsondata.rows[i].money == ""){
						$.messager.alert('提示','第'+index+'行承担金额填写不正确！');
						return ;
					}
					moneyTotal += parseFloat(jsondata.rows[i].money);
				}
				
				if(evlaArr == ""){
					$.messager.alert('提示',"请选择科目！");
					return;
				}
				param += "&details="+encodeURIComponent(evlaArr);
			}
			
			$(obj).hide();
			$.ajax({
				type:'POST',
				<%=isAdd?"url:'"+contextPath+"/springMVC/finance/addFinanceCommons',":"url:'"+contextPath+"/springMVC/finance/updateFinanceCommons?id="+id+"',"%>
				data:param,
				dataType:'json',
				success:function(rtJson){
					if(rtJson.rtState == '0'){
						eval('window.opener.<%=callback%>();');
						window.close();
					}
					else{
						$.messager.alert("提示",rtJson.rtMsrg);
					}
					$(obj).show();
				}
			});
		}
		
		function doSearch() {
			var dept_id = jQuery('#p_dept_id').combotree('getValue');
			var searchValue = jQuery('#searchValue').val();
			jQuery('#user_id').combogrid("grid").datagrid('load', {
				searchValue : searchValue,
				dept_id:dept_id
			});
		}
	</script>
	</head>
	<body>
		<div style="width: 97%;padding-left:10px">
		<form id="ff">
		<input type="hidden" id="creator" name="creator"/>
			<table  style="border-collapse: collapse;" width="100%" border="1px" bordercolor="#0eb83a">
				<tr>	
				    <td align="right" class="td1" nowrap>日期：</td>
					<td class="td2" nowrap >
						<input  id="operation_time" name="operation_time" class="easyui-datebox" data-options="required:true"/>
					</td>		
			        <td align="right" class="td1" nowrap>申请人：</td>
					<td class="td2" nowrap>
						<input type="text" id="user_id" name="user_id" data-options="required:true">
					</td>
				<tr>
				<tr>
					<td align="right" class="td1" nowrap>所属公司：</td>
					<td class="td2" nowrap>
						<input  id="company_id" name="company_id" class="easyui-combotree" data-options="required:true" >
					</td>
					<td align="right" class="td1" nowrap>确定承担部门：</td>
					<td class="td2" nowrap>
						<select id="is_all" name="is_all">
							<option value="0">确定</option>
							<option value="1">不确定</option>
						</select>
					</td>
				</tr>
				<tr>
					<td align="right" class="td1" nowrap>报销金额：</td>
					<td class="td2" nowrap colspan='3'>
						 <input id="money" name="money" class="easyui-numberbox" data-options="precision:2"  readonly="readonly"  value="0"/><span>(自动计算)</span>
					</td>
				</tr>
				<tr>
					<td align="right" class="td1" nowrap>摘要：</td>
					<td class="td2" nowrap colspan='3'>
						<textarea  id="summary" name="summary" rows="6" style="width: 100%"></textarea>
					</td>
				</tr>
				<%if(!"1".equals(isShow)){ %>
				<tr>
					<td align="right" class="td1" nowrap></td>
					<td class="td2" nowrap colspan='3'>
						<div align="left">
							<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-save',plain:false" onclick="addXMInvoiceRequest(this);">提交</a>
							<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-cancel',plain:false" onclick="javascript:window.close();">关闭</a>
						</div>
					</td>
				</tr>
				<%} %>
				<tr id="tableDiv">
					<td colspan="4"  nowrap>
						<div id="table"></div>
					</td>
				</tr>
			</table>
			</form>
		</div>
		<div id="tb" style="padding:3px;height:auto">
			<div align="right">
			             所属部门：<input  id="p_dept_id" name="p_dept_id"  style="width:150px"  class="easyui-combotree">
				查询条件：<input id="searchValue" name="searchValue" style="width:150px" title="用户名称或者用户真实姓名" placeholder="用户名称或者用户真实姓名"/>
				<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-search',plain:true" onclick="doSearch();"></a>
			</div>
		</div>
	</body>
</html>